package controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import service.impl.UserServiceImpl;
import entity.AjaxResult;
import entity.User;

@Controller
public class UserController {

	@Autowired
	private UserServiceImpl service;
	
	
	@RequestMapping("register")
	@ResponseBody
	public AjaxResult register(User u){
		//为新注册的用户添加默认数据
		u.setUemail(u.getUname()+"@qq.com");//默认邮箱
		u.setUheadPortrait("image/头像1.jpg");//默认头像
		u.setBalance(1);//默认余额
		u.setNickname(u.getUname()+"同学");//默认昵称
		//创建返回对象
		AjaxResult ajax=new AjaxResult();
		try {
			//调用注册方法，注册成功 返回success
			service.insertUser(u);
			ajax.setMsg("success");
		} catch (Exception e) {
			//注册失败，返回fail
			e.printStackTrace();
			ajax.setMsg("fail");
		}
		return ajax;
	}
	
	
	@RequestMapping("login")
	@ResponseBody
	public AjaxResult login(String username,String password,HttpSession session){
		//调用service登录方法
		User u =service.selectUser(username, password);
		//创建返回对象
		AjaxResult ajax=new AjaxResult();
		if(u==null){
			//登录失败
			ajax.setMsg("fail");
			session.invalidate();
		}else{
			//登录成功  
			ajax.setMsg("success");
			//将信息保存到session
			session.setAttribute("currentUser", u);
		}
		
		return ajax;
		
	}
	
	
}
